package com.bndg.littletor.ui.home

import android.content.res.AssetManager
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.MifareClassic
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.bndg.littletor.databinding.ActivityMainBinding
import com.bndg.littletor.databinding.ActivityNfcReaderBinding
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader

class NfcReaderActivity : AppCompatActivity() {

    private lateinit var binding: ActivityNfcReaderBinding
    private var nfcAdapter: NfcAdapter? = null

    // 添加类成员变量
    private val cardData = mutableMapOf<Int, MutableMap<Int, ByteArray>>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityNfcReaderBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initData()
    }

    var keys = mutableListOf<ByteArray>()
    fun initData() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        if (nfcAdapter == null) {
            // 设备不支持NFC
            finish()
        }
        keys.addAll(readKeysFromAssets(assets, "extended-std.keys"))
    }

    override fun onResume() {
        super.onResume()
        // 确保在前台时启用NFC读取
        val options = NfcAdapter.FLAG_READER_NFC_A or NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
        nfcAdapter?.enableReaderMode(this, ::onTagDiscovered, options, null)
    }

    override fun onPause() {
        super.onPause()
        // 在后台时禁用NFC读取
        nfcAdapter?.disableReaderMode(this)
    }

    fun readKeysFromAssets(assetManager: AssetManager, fileName: String): List<ByteArray> {
        val keys = mutableListOf<ByteArray>()
        try {
            // 打开文件并创建BufferedReader
            assetManager.open(fileName).use { inputStream ->
                BufferedReader(InputStreamReader(inputStream)).use { reader ->
                    var line: String?
                    while (reader.readLine().also { line = it } != null) {
                        // 过滤掉注释（以#开头）和空行
                        if (line?.startsWith("#") == false && line?.isNotBlank() == true) {
                            // 将十六进制字符串转换为ByteArray
                            keys.add(hexStringToByteArray(line!!))
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return keys
    }

    fun hexStringToByteArray(s: String): ByteArray {
        val clean = s.replace("[^0-9A-Fa-f]".toRegex(), "").uppercase()

        val len = clean.length
        if (len % 2 != 0) {
            throw IllegalArgumentException("长度必须是偶数：$len")
        }

        val data = ByteArray(len / 2)

        for (i in 0 until len step 2) {
            val firstChar = clean[i].toString()
            val secondChar = clean[i + 1].toString()

            // 手动将十六进制字符转为十进制整数
            val firstByte = Integer.parseInt(firstChar, 16)
            val secondByte = Integer.parseInt(secondChar, 16)

            // 合并成一个字节
            data[i / 2] = ((firstByte shl 4) or secondByte).toByte()
        }
        return data
    }

    private fun onTagDiscovered(tag: Tag) {
        Thread {
            try {
                val mifareTag = MifareClassic.get(tag)
                mifareTag.connect()
                // 默认密钥
                var sectorIndex = 0
                var usedKey: ByteArray = MifareClassic.KEY_DEFAULT
                while (sectorIndex < mifareTag.sectorCount) {
                    var authenticated = false
                    // 先试默认密钥
                    if (tryAuthenticateAndRead(mifareTag, sectorIndex, usedKey)) {
                        Log.d(">>>>", "扇区 $sectorIndex 使用默认密钥认证成功")
                        authenticated = true
                    } else {
                        Log.d(">>>>", "扇区 $sectorIndex 默认密钥失败，尝试其他密钥...")
                        for ((idx, key) in keys.withIndex()) {
                            if (tryAuthenticateAndRead(mifareTag, sectorIndex, key)) {
                                Log.d(
                                    ">>>>",
                                    "扇区 $sectorIndex 使用密钥 ${key.toHex()} 成功（第${idx + 1}个密钥）"
                                )
                                authenticated = true
                                usedKey = key
                                break
                            } else {
//                                Trace.d("扇区 $sectorIndex 第${idx + 1}个密钥失败：${key.toHex()}")
                            }
                        }
                    }
                    if (!authenticated) {
                        Log.d(">>>>", "扇区 $sectorIndex 所有密钥尝试失败！")
                    }
                    sectorIndex++
                }
                mifareTag.close()
                updateCardDataDisplay() // 更新 UI 显示
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }.start()
    }

    fun tryAuthenticateAndRead(tag: MifareClassic, sectorIndex: Int, key: ByteArray): Boolean {
        return try {
            if (tag.authenticateSectorWithKeyA(sectorIndex, key)) {
                val blockCount = tag.getBlockCountInSector(sectorIndex)
                for (blockIndexInSector in 0 until blockCount) {
                    val blockIndex = tag.sectorToBlock(sectorIndex) + blockIndexInSector
                    val data = tag.readBlock(blockIndex)
                    cardData.getOrPut(sectorIndex) { mutableMapOf() }[blockIndexInSector] = data
                }
                true
            } else {
                false
            }
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }
    }

    private fun updateCardDataDisplay() {
        runOnUiThread {
            val sb = StringBuilder()

            for ((sector, blocks) in cardData.toSortedMap()) {
                sb.append("扇区 $sector\n")
                for ((block, data) in blocks.toSortedMap()) {
                    sb.append("  块 $block: ${data.toHex()}\n")
                }
                sb.append("\n")
            }
            // 找到 TextView 并设置内容
            binding.tvCardData.text = sb.toString()
        }
    }

    fun ByteArray.toHex(): String {
        return joinToString(separator = "") { byte ->
            "%02X".format(byte.toInt() and 0xFF)
        }
    }

    // 辅助函数：检查字节数组是否全为00
    fun isAllZero(data: ByteArray): Boolean {
        data.forEach { byte ->
            if (byte.toInt() != 0) return false
        }
        return true
    }
}